import config from '@/config/index.js'
import fun from '@/utils/common.js'

const isshow = process.env.VUE_APP_PLATFORM; //设备类型
let sendSum = 0 // 需要展示 Loading发送请求的数量 为0才关闭
let sendTime

import useUserInfoStore from '@/stores/user.js';
import { storeToRefs } from 'pinia';
const userStore = useUserInfoStore();
const { isLogin } = storeToRefs(userStore);

function request(uri, method, data, query, is_login) {
	// 是否是微信浏览器
	let isWeChat = false

	function isWeChatBrowser() {
		// 获取用户代理字符串
		const userAgent = navigator.userAgent.toLowerCase();
		// 判断是否包含 "micromessenger"
		return userAgent.indexOf('micromessenger') > -1;
	}

	if (isshow == 'h5') {
		if (isWeChatBrowser()) {
			// console.log('当前环境是微信浏览器');
			isWeChat = true
		} else {
			// console.log('当前环境不是微信浏览器');
			isWeChat = false
		}
	}

	let header = {
		// 'X-Requested-With': 'XMLHttpRequest',
		// 'App-Source': config.app_source,
		// 'App-Version': config.app_version
	}
	if (is_login) {
		// header['Authorization'] = 'Bearer ' + fun.getToken()
		header['Authorization'] = fun.getToken()
	}
	let url = fun.genUrl(config.api_base_url + uri, query)
	return new Promise((resolve, reject) => {
		if (data.loding || query.loding) {
			sendSum += 1;
			uni.showLoading({
				title: '加载中...',
				mask: true
			})
		};
		uni.request({
			url: url,
			method: method,
			header: header,
			data: data,
			timeout: config.api_timeout,
			success: response => {
				let res = response.data;

				if (data.returnAll == 1 || query.returnAll == 1) {
					return resolve(res)
				}
				if (res.code == 200) {
					return resolve(res.data)
				} else if (res.code == 401) { //token无效
					uni.showToast({
						title: '登录已过期，请重新登录',
						icon: 'none'
					})
					fun.setToken('')
					isLogin.value = false
					fun.getPageUrl()
					
				}

				sendSum = 0
				return reject(new Error(res.message || 'Error'))
			},
			fail: error => {
				sendSum = 0
				if (data.returnAll == 1) {
					return resolve(error)
				}
				uni.showToast({
					title: "网络异常2" + JSON.stringify(error),
					icon: 'none'
				})
				console.error(error);
				return reject(error)
			},
			complete() {
				if (data.loding || query.loding) {
					sendSum -= 1;
					clearTimeout(sendTime)
					sendTime = setTimeout(() => {
						if (sendSum === 0 || sendSum < 0) {
							uni.hideLoading();
							sendSum = 0
						};
					}, 200)
				}
			}
		})
	})
}

function get(url, query = {}, is_login = true) {
	return request(url, 'GET', {}, query, is_login)
}

function post(url, data = {}, query = {}, is_login = true) {
	return request(url, 'POST', data, query, is_login)
}

function put(url, data = {}, query = {}, is_login = true) {
	return request(url, 'PUT', data, query, is_login)
}

function del(url, data = {}, query = {}, is_login = true) {
	return request(url, 'DELETE', data, query, is_login)
}
export default {
	get,
	post,
	put,
	del
}